package com.pgybook.front.web.interceptors;

import com.pgybook.db.entity.domain.Customer;
import com.pgybook.front.service.MemberService;
import com.pgybook.front.web.util.FrontUtil;
import jodd.typeconverter.Convert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Created with IntelliJ IDEA.
 * User: feeling
 * Date: 13-11-21
 * Time: 下午5:05
 */
public class PreLoadCustomerInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession(false);
        if (session != null) {
            Long custId = Convert.toLong(session.getAttribute("custId"), null);
            if (custId != null) {
                Customer cust = memberSrv.getCustomer(custId);
                if (cust != null) {
                    request.setAttribute(FrontUtil.CUSTOMER_KEY, cust);
                }
            }
        }
        return super.preHandle(request, response, handler);
    }

    @Autowired
    private MemberService memberSrv;

}
